import { Map, View, Extent } from 'ol'
import TileLayer from 'ol/layer/Tile'

import OSM from 'ol/source/OSM'
import TileArcGISRest from 'ol/source/TileArcGISRest'

import { fromLonLat, transformExtent } from 'ol/proj'

import { defaults } from 'ol/control'
import ScaleLine from 'ol/control/ScaleLine'

/**
 * 初始化地图
 * @param {*} mapDiv
 */
export const initMap = (mapDiv, vm) => {
  window.olMap = null

  // 视角
  const extent = [-200, -85, 410, 85]
  const view = new View({
    // projection: 'EPSG:4326',
    // center: [113, 36],
    projection: 'EPSG:3857',
    center: fromLonLat([103.103, 31.990]),
    extent: transformExtent(extent, 'EPSG:4326', 'EPSG:3857'),
    zoom: 4,
    maxZoom: 20,
    minZoom: 3
  })
  // 图层
  const layer1 = new TileLayer({
    source: new OSM(),
    preload: Infinity
  })
  const layer2 = new TileLayer({
    source: new TileArcGISRest({
      url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
    }),
    preload: Infinity
  })
  const layer3 = new TileLayer({
    source: new TileArcGISRest({
      url: 'https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer'
    }),
    preload: Infinity
  })
  // 控制
  // eslint-disable-next-line new-cap
  const controls = new defaults({ attribution: false, zoom: false, rotate: false })

  const olMap = new Map({
    target: mapDiv,
    layers: [layer2],
    view: view,
    controls: controls
  })

  // 实例化比例尺控件
  var scaleLineControl = new ScaleLine({
    // 设置度量单位为米
    units: 'metric',
    target: 'scale-bar',
    className: 'ol-scale-line'
  })
  // 将比例尺控件加入到map中
  olMap.addControl(scaleLineControl)

  window.olMap = olMap

  if (vm) vm.$bus.$emit('mapIsInit')
}
